package rentel.logbook.car;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import rentel.logbook.persistence.DBService;

/**
 * Car MVC controller
 * @author Jiri Styblo
 *
 */
@SessionAttributes({"addcar"})
@Controller
public class CarController {
	
	private static java.util.logging.Logger logger = Logger.getLogger(
		CarController.class.getName()
	);

	private static final String CAR_SAVE_SUCCESSFUL = "Car save successful."; 
	
	@ModelAttribute("addcar")
	public Car init() {
	    return new Car();
	}
	
	@RequestMapping(value = "/addcar", method = RequestMethod.GET)
	public String viewForm() {
		return "addcar";
	}

    @RequestMapping(value = "/addcar", method = RequestMethod.POST)
    public String saveForm(
    	@ModelAttribute("addcar") Car car,
    	BindingResult result,
    	ModelMap model
    ) {

    	CarFormValidator carFormValidator = new CarFormValidator();
		carFormValidator.validate(car, result);
		
    	if (result.hasErrors()) {
    		// TODO It can be very talkative!
    		logger.log(Level.INFO, "Wrong data input.");
    		
    		return "addcar";

    	} else {
    		// Save submitted data
    		DBService.add(car);
		
    		model.addAttribute("ok_message", CAR_SAVE_SUCCESSFUL);
    		
    		return "succes";
    	}
    }
}
